<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam"
      :data-callback="dataCallback" data-key="userPageListVoList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <SButton :buttonProps="{ type: 'primary' }" buttonText="添加" />
        <SButton :buttonProps="{ type: 'primary' }" buttonText="移除" />
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="变更" />
        <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="移除" />
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { User } from "@/api/interface";
import { useHandleData, useHandleOperation } from "@/hooks/useHandleData";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import ProTable from "@/components/ProTable/index.vue";
import UserDialog from "./RolePersonDialog.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { getUserList, editUser, addUser, resetUserPassWord, userDisable } from "@/api/modules/user";
import SButton from "@/components/SButton/index.vue";
import ImportDialog from "@/components/ImportExport/ImportDialog.vue";
import ExportDialog from '@/components/ImportExport/ExportDialog.vue';

import { ElMessage, ElMessageBox } from "element-plus";
import { useDataStore } from '@/stores/modules/data'
import { getRoleUserList } from "@/api/modules/role";
import { useRoute } from "vue-router";

const dataStore = useDataStore()

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive<any>({ roleId: undefined });
const route = useRoute();
watch(() => route.query, (newValue) => {
  initParam.roleId = newValue.roleId;
})


// console.log('initParam', initParam);


// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data._embedded.userListPaginationQueryInformationDTOList,
    total: data.page.totalElements
  };
};

const getTableList = (params: any) => {

  return getRoleUserList(params);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();
onMounted(async () => {
  await dataStore.fetchRoleList();
  await dataStore.fetchDepartmentList()
});

const roleList = computed(() => dataStore.roleList);
const departmentList = computed(() => dataStore.departmentList);
const deptList = computed(() => dataStore.deptList);
console.log('departmentList', departmentList);


// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  {
    prop: "username",
    label: "人员名称",
    search: { el: "input" }
  },
  {
    prop: "deptName", label: "部门", search: { el: "tree-select", props: { filterable: true } },
    // enum: deptList,
    // fieldNames: { label: "deptName", value: "deptId" },
  },
  {
    prop: "workNumber",
    label: "工号",
    search: { el: "input" },
  },
  { prop: "operation", label: "操作", fixed: "right" }
]);

//禁用
const handleDisable = (row: any, e: any) => {
  userDisable(row.id).then(() => {
    ElMessage.success({ message: '禁用成功' });
    proTable.value?.getTableList();
  }).catch((err) => {
    ElMessage.error({ message: '禁用失败' });
  })
}

// 重置用户密码
const resetPass = async (params: User.ResUserList) => {
  await useHandleOperation(resetUserPassWord, { id: params.id, newPassword: 'zs123456' }, params.username);
  proTable.value?.getTableList();
};

// 打开 dialog(新增、查看、编辑)
const dialogTitle = ref('');
const dialogVisible = ref(false);
const selectedRow = ref<Partial<User.ResUserList>>({});
const userDialogRef = ref<InstanceType<typeof UserDialog> | null>(null);

const openDialog = (title: string, row: Partial<User.ResUserList> = {}) => {
  dialogTitle.value = title;
  selectedRow.value = row;
  dialogVisible.value = true;
  userDialogRef.value?.acceptParams({
    title,
    isView: title === '详情',
    row,
    api: title === '新增' ? addUser : editUser,
    getTableList: proTable.value?.getTableList
  });
};

//导入
const importUserInfoRef = ref<InstanceType<typeof ImportDialog> | null>(null);
const importUserInfoVisible = ref(false);
const templateName = '用户信息';
const templateUrl = '/path/to/template.xlsx';
const uploadAction = 'https://jsonplaceholder.typicode.com/posts/';
const importUserInfo = async () => {
  importUserInfoVisible.value = true;
};
const handleImportOk = async () => {
  importUserInfoVisible.value = false;
  proTable.value?.getTableList();
}

//导出
const exportUserInfoRef = ref<InstanceType<typeof ExportDialog> | null>(null);
const exportUserInfoVisible = ref(false);
const selectedItems = [];

const cities = ['序号', '姓名', '性别', '年龄', '账号', '密码', '所属部门', '创建时间', '密码', '创建人', '身份证号码'];

const exportUserInfo = async () => {
  exportUserInfoVisible.value = true;
};

const handleExportOk = async () => {
  exportUserInfoVisible.value = false;
};

//离职
const leaveVisible = ref(false);
const rowId = ref<any>()
const leaveTitle = ref('')
const handleLeave = (row: User.ResUserList) => {
  rowId.value = Number(row.id)
  leaveTitle.value = `离职：${row.username}`
  leaveVisible.value = true;
};

const handleLeaveOk = async () => {
  leaveVisible.value = false;
  proTable.value?.getTableList();
}

//已选择数据
const handleSelected = (row: any) => {
  console.log(row);
}


</script>
